package com.example.msm.controller;

import com.example.msm.service.MsmService;
import com.example.msm.utils.RandomUtil;
import com.example.utils.CommonResult;
import org.reflections.util.Utils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

//@CrossOrigin
@RestController
@RequestMapping("/edumsm/msm")
public class MsmController {

    @Resource
    MsmService msmService;
    @Resource
    RedisTemplate<String,String> redisTemplate;

    //发送短信
    @GetMapping(value = "send/{phone}")
    public CommonResult send(@PathVariable String phone){
        //1.判断该手机号最近5分钟是否已发送过短信
        String isSended = (String) redisTemplate.opsForValue().get(phone);
        if(!Utils.isEmpty(isSended)){
            return CommonResult.ok();
        }
        //2.为空，发送短信
        String code= RandomUtil.getFourBitRandom();
        boolean isSend=msmService.send(phone,code);
        //3.判断发送结果
        if (isSend){
            //4.发送成功，将验证码存入redis
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return CommonResult.ok();
        }else {
            return CommonResult.error().message("发送验证码失败");
        }
    }
}
